package com.stationbuilding.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;
import com.google.gson.Gson;
import com.stationbuilding.R;
import com.stationbuilding.api.RetrofitManager;
import com.stationbuilding.bean.LoginResultBean;
import com.stationbuilding.bean.ResultBean;
import com.stationbuilding.bean.UserBean;
import com.stationbuilding.bean.UserInfoBean;
import com.stationbuilding.utils.Constants;
import com.stationbuilding.utils.JSONUtil;
import com.stationbuilding.utils.PreferenceHelper;
import com.stationbuilding.utils.DialogUtils;
//import com.zhy.http.okhttp.callback.StringCallback;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * 登陆页面
 */
public class WelcomeActivity extends Activity {
    private Dialog dialog;
    private EditText username, password;
    private Button loginBtn;
    private PreferenceHelper preferenceHelper;
    private String preUsername;
    private String prePassword;
    private CheckBox rememberPsd;
    private boolean isChecked;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);
        preferenceHelper = PreferenceHelper.getInstance(WelcomeActivity.this);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
        loginBtn = (Button) findViewById(R.id.loginbtn);
        rememberPsd = (CheckBox) findViewById(R.id.cb_rememberpd);
        rememberPsd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                isChecked = b;
            }
        });
        //进入页面后取出保存在sp里的账号密码
        if (preferenceHelper.getAccount() != null) {
            preUsername = preferenceHelper.getAccount();
            prePassword = preferenceHelper.getPassword();
            if (!TextUtils.isEmpty(preUsername)) {
                username.setText(preUsername);
            }
            if (!TextUtils.isEmpty(prePassword)) {
                password.setText(prePassword);
                rememberPsd.setChecked(true);
            }
        }
        // 登陆按钮点击事件，点击走登陆方法
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login(username.getText().toString(), password.getText().toString());
            }
        });
    }

    /**
     * 登陆方法
     *
     * @param username 用户名字符串
     * @param password 密码字符串
     */
    public void login(final String username, final String password) {
        startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        finish();
        RetrofitManager.toSubscribe(RetrofitManager.getApiService().login(username, password), new Observer<LoginResultBean>() {
            @Override
            public void onSubscribe(@io.reactivex.annotations.NonNull Disposable d) {
                dialog = DialogUtils.createLoadingDialog(WelcomeActivity.this, "加载中...");
            }

            @Override
            public void onComplete() {
                DialogUtils.closeDialog(dialog);
            }

            @Override
            public void onError(Throwable e) {
                DialogUtils.closeDialog(dialog);
                Toast.makeText(WelcomeActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNext(LoginResultBean loginResultBean) {
                if (loginResultBean.getCode() == 0) {
                    saveUserInfo(loginResultBean.getUserInfo());
                } else {
                    Toast.makeText(WelcomeActivity.this, loginResultBean.getCode().toString(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void saveUserInfo(UserInfoBean userInfoBean) {
        // token信息
        preferenceHelper.saveToken(userInfoBean.getToken());
        // 登录用户信息
        UserBean userBean = userInfoBean.getUser();
        preferenceHelper.saveUserId(userBean.getUserId());
        preferenceHelper.saveUserName(userBean.getUsername());
        preferenceHelper.saveRoleIdList(userBean.getRoleIdList().toString());
        preferenceHelper.saveAccount(userBean.getAccount());
        // 记住密码
        if (isChecked) {
            preferenceHelper.savePassword(password.getText().toString());
        } else {
            preferenceHelper.cleanPassword();
        }
        //成功后跳转MainActivity
        startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        finish();
    }
}